import React, { useEffect, useState } from 'react'
import { SearchBar } from '@nutui/nutui-react';
import '@nutui/nutui-react/dist/style.css'
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import {Button} from 'antd'
import {  List } from 'antd-mobile'

export default function Search() {
  let navigate = useNavigate();
  const [name,setName] = useState('');
  let [arr,setArr] = useState([])
  let [data,setData] = useState([])
  useEffect(()=>{
    getarr()
  },[])

  let getarr = async()=>{
    let {data:{list}} = await axios.get("http://localhost:3000/gethistory")
    setArr(list)
  }
  let gsearch = ()=>{
    setName(name)
    if(arr.length>=10){
      add(name)
      del(arr[arr.length-1]._id)
    }else{
      add(name)
    }
    

  }
  let add = async(name)=>{
    let obj = {
      name:name
    }
    await axios.post("http://localhost:3000/addhistory",obj)
    let res = await axios.get("http://localhost:3000/getdata",{params:{name}})
    setData(res.data.list)
    getarr()
  }

  let delall = async()=>{
    await axios.get("http://localhost:3000/delallhistory")
    getarr()
  }
  let del = async(id)=>{
    await axios.get("http://localhost:3000/delhistory?",{params:{"_id":id}})
    getarr()
  }
  return (
    <div>
      <div style={{display:"flex"}}>
      <span style={{backgroundColor:"rgb(246,246,246)",marginTop:"5px"}} onClick={()=>{navigate("/app/home")}}>取消</span><SearchBar maxLength={10} onChange={(e)=>setName(e)} value={name} style={{width:"83%"}}/><span style={{backgroundColor:"rgb(246,246,246)",marginTop:"5px"}} onClick={gsearch}>搜索</span>
      </div>
        
        <p style={{fontSize:"15px"}}>历史搜索</p>
        <div style={{display:"flex",justifyContent:"space-around",flexWrap:"wrap",width:"100%",height:"60px"}}>
            {
              arr.map((item)=>{
                return <Button key={item._id} style={{marginTop:"5px"}}>
                  {item.name}
                </Button>
              })
            }
        </div>
        <div style={{width:"100%",height:"20px"}}></div>
        <List>
        {data.map(item => (
          <List.Item key={item._id}  >
            <div style={{ position: "relative", display: "flex", justifyContent: "space-around", margin: "auto", backgroundColor: "" }} onClick={()=>navigate(`/context?id=${item._id}`)}>
              <div style={{ width: "50%" }}>
                <p style={{ width: "45%", fontWeight: "bolder", cursor: "point", position: "absolute", fontSize: '15px', top: "25px", left: "20px" }}>{item.title}</p>
              </div>
              <div style={{ width: "50%", marginLeft: "25px", height: "110px", paddingTop: "15px" }}>
                <img src={item.img} alt="" style={{ width: "160px", height: "100px", borderRadius: "5%" }} />
              </div>
            </div>
          </List.Item>
        ))}
      </List>
        <p onClick={delall} style={{fontSize:"15px",textAlign:"center"}}>清除历史数据</p>
    </div>
  )
}
